/******************************************************************************
 * @File name   :      ResetPasswordServiceImpl.java
 *
 * @Author      :      chen shixiang
 *
 * @Date        :      2011-6-22
 *
 * @Copyright Notice: 
 * Copyright (c) 2014 DMS, Inc. All  Rights Reserved.
 * This software is published under the terms of the DMS Software
 * License version 1.0, a copy of which has been included with this
 * distribution in the LICENSE.txt file.
 * 
 * 
 * ----------------------------------------------------------------------------
 * Date                   Who         Version        Comments
 * 2011-6-22 上午09:52:46        chen shixiang     1.0            Initial Version
 * 2011-9-16 下午01:42:11        He Hao     1.1            Add Method validationUser
 * 2011-9-16 下午05:42:11        He Hao     1.2            Change Method validationUser
 * 2011-10-25 上午11:00:50        HeHao       1.3             Add Method sendMessage
 *****************************************************************************/
package com.cap.bts.framework.ge.resetpassword.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.cap.bts.commonfunc.common.constant.BusinessTypeConstants;
import com.cap.bts.commonfunc.common.constant.SmsTemplateNoConstants;
import com.cap.bts.commonfunc.common.constant.SmsTemplateVariable;
import com.cap.bts.commonfunc.common.dto.SmsContentDetailDto;
import com.cap.bts.crmdp.dealer.masterdata.domain.MasterDataDealerInfo;
import com.cap.bts.crmdp.dealer.masterdata.service.IMaintainDealerService;
import com.cap.bts.crmdp.dealer.member.domain.MemberInfo;
import com.cap.bts.framework.codemapping.domain.CodeInfo;
import com.cap.bts.framework.codemapping.service.ICodeMapping;
import com.cap.bts.framework.common.constant.CommonErrorConstants;
import com.cap.bts.framework.common.exception.AppException;
import com.cap.bts.framework.common.service.impl.BaseServiceImpl;
import com.cap.bts.framework.common.util.Utils;
import com.cap.bts.framework.ge.resetpassword.dao.IResetPasswordDao;
import com.cap.bts.framework.ge.resetpassword.dto.CertificateDto;
import com.cap.bts.framework.ge.resetpassword.dto.ResetPasswordDto;
import com.cap.bts.framework.ge.resetpassword.dto.UserInfoDto;
import com.cap.bts.framework.ge.resetpassword.service.IResetPasswordService;
import com.cap.bts.framework.sms.service.ISmContentService;
import com.cap.bts.framework.usermgnt.domain.EmployeeInfo;
import com.cap.bts.framework.usermgnt.domain.User;
import com.cap.bts.framework.usermgnt.service.IEmployeeInfoService;
import com.cap.bts.framework.usermgnt.service.IUserMgntService;
import com.cap.bts.framework.usermgnt.util.PasswordUtil;
import com.cap.bts.framework.workbench.userlogin.dto.OperationPwdDto;

/**
 *
 */
@Transactional(rollbackFor=AppException.class)
@Service
public class ResetPasswordServiceImpl extends BaseServiceImpl implements IResetPasswordService {

    @Resource(name="resetPasswordDao")
    IResetPasswordDao resetPasswordDao;
    @Resource(name="userMgntServiceImpl")
    IUserMgntService userMgntService;
    @Resource(name="codeMappingImpl")
    ICodeMapping codeMapping;

    @Resource(name="employeeInfoServiceImpl")
    private IEmployeeInfoService employeeInfoService;
    @Autowired
    private IMaintainDealerService maintainDealerService;
    
    @Autowired
    ISmContentService smContentService;

    /**
     * {@inheritDoc} 
     * overridden:
     * @throws AppException  AppException
     * @Date        :      2011-6-22
     * @see com.cap.bts.dms.ge.resetpassword.service.IResetPasswordService#generateNewPassword()
    **/
    @Override
    public String generateNewPassword()throws AppException {
        return PasswordUtil.getRandom();
    }

    /**
     * {@inheritDoc} 
     * overridden:
     * @throws AppException  AppException
     * @Date        :      2011-6-22
     * @see com.cap.bts.dms.ge.resetpassword.service.IResetPasswordService#getUserCertificateType(java.lang.String)
    **/
    @Override
    public CertificateDto getUserCertificateType(String userCode)throws AppException {
        CertificateDto dto = resetPasswordDao.getUserCertificateType(userCode);
        if(dto!=null){
            CodeInfo cInfo = codeMapping.findById(dto.getCertificateTypeId());
            dto.setCertificateType(cInfo.getValue());
        }
        return dto;
    }

    /**
     * {@inheritDoc} 
     * overridden:
     * @throws AppException  AppException
     * @Date        :      2011-6-22
     * @see com.cap.bts.dms.ge.resetpassword.service.IResetPasswordService#getUserMobilePhone(java.lang.String)
    **/
    @Override
    public Long getUserMobilePhone(String userCode)throws AppException {
        return resetPasswordDao.getUserMobilePhone(userCode);
    }

    /**
     * {@inheritDoc} 
     * overridden:
     * @throws AppException  AppException
     * @Date        :      2011-6-22
     * @see com.cap.bts.dms.ge.resetpassword.service.IResetPasswordService#sendNewPassword(java.lang.String, java.lang.String)
    **/
    @Override
    public void sendNewPassword(String userCode, String newPassword)throws AppException {
        // TODO Auto-generated method stub
        
    }

    /**
     * {@inheritDoc} 
     * overridden:
     * @throws AppException  AppException
     * @Date        :      2011-6-22
     * @see com.cap.bts.dms.ge.resetpassword.service.IResetPasswordService#updatePassword(java.lang.String, java.lang.String, long)
    **/
    @Override
    public boolean updatePassword(String userCode, String password, long operatorId) throws AppException {
        User user = userMgntService.getUserByUserCode(userCode);
        
        user.setPassword(PasswordUtil.encodePassword(password));
        user.setLastUpdateBy(operatorId);
        return userMgntService.updateUser(user);
    }

    /**
     * {@inheritDoc} 
     * overridden:
     * @throws AppException  AppException
     * @Date        :      2011-6-22
     * @see com.cap.bts.dms.ge.resetpassword.service.IResetPasswordService#verifyResetPasswordRequest(com.cap.bts.dms.ge.resetpassword.dto.ResetPasswordDto)
    **/
    @Override
    public boolean verifyResetPasswordRequest(ResetPasswordDto resetPasswordDto)throws AppException {
        User user = userMgntService.getUserByUserCode(resetPasswordDto.getUserCode());
        if(user == null){
            return false;
        }else{
            try {
//              boolean has = resetPasswordDao.verifyResetPasswordRequest(resetPasswordDto);
              //if(has){
                   String newPwd = generateNewPassword(); //得到八位数的随机密码
                   //Long mobilePhone = getUserMobilePhone(resetPasswordDto.getUserCode());//获取用户的手机号码
                   updatePassword(resetPasswordDto.getUserCode(), newPwd, user.getId()); //跟新数据库的密码
                   return true;
                   
//                   IMessageSender messageSender = new MessageSenderImpl();
//                   short messagePriority = 3;
//                   Long mobile = mobilePhone;
//                   String templateName = "resetpassword.txt";
//                   HashMap<String, String> valueMap = new HashMap<String, String> ();
//                   valueMap.put("password", newPwd);
//                   TextMessage tm = new TextMessage();
//                   tm.setMessagePriority(messagePriority);
//                   tm.setMobile(mobile+"");
                   //messageSender.sendMessage(tm, templateName, valueMap);//TODO 发送新密码到手机
                   //sendMessage(user, newPwd, mobilePhone);
              //}
          } catch (Exception e) {
              throw new AppException(CommonErrorConstants.SYSTEM_ERROR,user.getUserCode() + " update password error");
          }
        }
         
    }

    /**
     * @Date        :      2011-10-18
     * @param user
     * @param newPwd
     * @param mobilePhone
     * @throws AppException
     */
    @Override
    public void sendMessage(User user, String newPwd, Long mobilePhone) throws AppException {
        //if(user.getBrandId()!=BrandConstants.CAD){
             EmployeeInfo employee = employeeInfoService.getEmployeeInfoById(user.getEmployeeId());
             SmsContentDetailDto smsDto = new SmsContentDetailDto();
             smsDto.setBrandId(user.getBrandId());
             smsDto.setDealerId(employee.getDealerId());
             smsDto.setTemplateNo(SmsTemplateNoConstants.FIND_PASSWORD_TEMPLATE_NO);
             smsDto.setNotificationDate(new Date());
             Map<String,String> paraMap = new HashMap<String, String>();
             paraMap.put(SmsTemplateVariable.VARIABLE_USER_NAME, user.getName());
             paraMap.put(SmsTemplateVariable.VARIABLE_USER_CODE, user.getUserCode());
             paraMap.put(SmsTemplateVariable.VARIABLE_PASSWORD, newPwd);
             smsDto.setParaMap(paraMap);
             smsDto.setBusinessItemId(user.getId());
             smsDto.setBusinessType(BusinessTypeConstants.FIND_PASSWORD);
             smsDto.setDestMobile(mobilePhone);
       // }
    }

    /**
     * {@inheritDoc} 
     * overridden:
     * @Date        :      Sep 16, 2011
     * @see com.cap.bts.dms.ge.resetpassword.service.IResetPasswordService#validationUser(com.cap.bts.dms.ge.resetpassword.dto.ResetPasswordDto)
    **/
    @Override
    public boolean validationUser(ResetPasswordDto resetPasswordDto) throws AppException {
       return resetPasswordDao.verifyResetPasswordRequest(resetPasswordDto);
    }

    /**
     * {@inheritDoc} 
     * overridden:
     * @Date        :      2015年7月16日
     * @see com.cap.bts.framework.ge.resetpassword.service.IResetPasswordService#getUserMobilePhoneFromDealer(java.lang.String)
    **/
    @Override
    public String getUserMobilePhoneFromDealer(String userCode) throws AppException {
        return resetPasswordDao.getUserMobilePhoneFromDealer(userCode);
    }

    /**
     * {@inheritDoc} 
     * overridden:
     * @Date        :      2015年7月16日
     * @see com.cap.bts.framework.ge.resetpassword.service.IResetPasswordService#verifyResetPasswordRequest(com.cap.bts.framework.ge.resetpassword.dto.UserInfoDto)
    **/
    @Override
    public UserInfoDto verifyResetPasswordRequest(UserInfoDto userInfoDto) throws AppException {
        User user = userMgntService.getUserByUserCode(userInfoDto.getUserCode());
        if(user == null){
            userInfoDto.setExist(false);
        }else{
            try {
                   String newPwd = generateNewPassword(); //得到八位数的随机密码
                   updatePassword(userInfoDto.getUserCode(), newPwd, user.getId()); //跟新数据库的密码
                   userInfoDto.setNewPwd(newPwd);
                   String mobile = getUserMobilePhoneFromDealer(userInfoDto.getUserCode());
                   userInfoDto.setMobile(mobile);
                   userInfoDto.setNewPwd(newPwd);
                   userInfoDto.setExist(true);
                   user.setLastLoginTime(null);
                   //send sms
                   Map<String, String> paraMap = new HashMap<String, String>();
                   paraMap.put(SmsTemplateVariable.VARIABLE_USER_CODE, userInfoDto.getUserCode());
                   paraMap.put(SmsTemplateVariable.VARIABLE_PASSWORD, newPwd);
                   SmsContentDetailDto smsDto = new SmsContentDetailDto();
                   smsDto.setParaMap(paraMap);
                   if (Utils.notEmpty(mobile)) {
                        smsDto.setDestMobile(Long.valueOf(mobile));
                        smsDto.setTemplateNo(SmsTemplateNoConstants.FIND_PASSWORD_TEMPLATE_NO);
                        smContentService.createSmsContent(smsDto);
                   }
          } catch (Exception e) {
              throw new AppException(CommonErrorConstants.SYSTEM_ERROR,user.getUserCode() + " update password error");
          }
        }
        return userInfoDto;
    }

    /**
     * {@inheritDoc} 
     * overridden:
     * @Date        :      2015年7月27日
     * @see com.cap.bts.framework.ge.resetpassword.service.IResetPasswordService#verifyResetOperationPwdRequest(com.cap.bts.framework.workbench.userlogin.dto.OperationPwdDto)
    **/
    @Override
    public OperationPwdDto verifyResetOperationPwdRequest(OperationPwdDto operationPwdDto)
        throws AppException {
        MasterDataDealerInfo masterDataDealerInfo = maintainDealerService.getDealerByDealerNum(operationPwdDto.getDealerNum());
        if(masterDataDealerInfo == null){
            operationPwdDto.setExist(false);
        }else{
            if(masterDataDealerInfo != null){
                try {
                    String newPwd = generateNewPassword(); //得到八位数的随机密码
                    updateOperationPassword(masterDataDealerInfo.getDealerNum(),newPwd);
                    operationPwdDto.setOperationPassword(newPwd);
                    operationPwdDto.setExist(true);
                    operationPwdDto.setContactPhone(masterDataDealerInfo.getContactPhone());
                    masterDataDealerInfo.setLastOpreationPwdChangeTime(null);
                    //send sms message
                    Map<String, String> paraMap = new HashMap<String, String>();
                    paraMap.put(SmsTemplateVariable.VARIABLE_PASSWORD, newPwd);
                    SmsContentDetailDto smsDto = new SmsContentDetailDto();
                    smsDto.setParaMap(paraMap);
                    if (Utils.notEmpty(masterDataDealerInfo.getContactPhone())) {
                         smsDto.setDestMobile(Long.valueOf(masterDataDealerInfo.getContactPhone()));
                         smsDto.setTemplateNo(SmsTemplateNoConstants.FIND_CERTIFICATION_PASSWORD_TEMPLATE_NO);
                         smContentService.createSmsContent(smsDto);
                    }
                } catch (Exception e) {
                    throw new AppException(CommonErrorConstants.SYSTEM_ERROR,operationPwdDto.getDealerNum() + " update operationPassword error");
                }
            }
        }
        return operationPwdDto;
    }

    /**
     * {@inheritDoc} 
     * overridden:
     * @Date        :      2015年7月27日
     * @see com.cap.bts.framework.ge.resetpassword.service.IResetPasswordService#updateOperationPassword(java.lang.String)
    **/
    @Override
    public boolean updateOperationPassword(String dealerNum,String newPwd) throws AppException {
        MasterDataDealerInfo masterDataDealerInfo = maintainDealerService.getDealerByDealerNum(dealerNum);
        masterDataDealerInfo.setOperationPassword(PasswordUtil.encodePassword(newPwd));
        return maintainDealerService.updateDealer(masterDataDealerInfo);
    }     
}

